package com.jiayu.seckilldemo.controller;


import com.jiayu.seckilldemo.pojo.User;
import com.jiayu.seckilldemo.service.IGoodsService;
import com.jiayu.seckilldemo.service.IUserService;
import com.jiayu.seckilldemo.vo.DetailVo;
import com.jiayu.seckilldemo.vo.GoodsVo;
import com.jiayu.seckilldemo.vo.RespBean;
import com.jiayu.seckilldemo.vo.RespBeanEnum;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author jiayu
 * @since 2022-07-20
 */
@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 跳转登录页 (优化缓存）
     * @param model
     * @param user
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("商品列表")
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //Redis中获取页面，如果不为空，直接返回页面
        String html = (String) valueOperations.get("goodsList");
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());
        // return "goodsList";
        //如果为空，手动渲染，存入Redis并返回
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (!StringUtils.isEmpty(html)) {
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }



    /**
     * 跳转商品详情页(实现页面静态化）
     * @param user
     * @param goodsId
     * @return
     */
    @ApiOperation("商品详情")
    @RequestMapping(value = "/detail/{goodsId}",method = RequestMethod.GET)
    @ResponseBody
    public RespBean toDetail(HttpServletRequest request,HttpServletResponse response,
                             Model model,User user, @PathVariable Long goodsId) {

        System.out.println("/detail/{goodsId}的user为"+user.toString());
        System.out.println("/detail/{goodsId}的goodsid为"+goodsId);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int seckillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        if (nowDate.before(startDate)) {
            //秒杀还未开始0
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) {
            //秒杀已经结束
            seckillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            seckillStatus = 1;
            remainSeconds = 0;
        }
        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setRemainSeconds(remainSeconds);
        detailVo.setSecKillStatus(seckillStatus);
        System.out.println("/detail/{goodsId}的detailVo为"+detailVo.toString());
        return RespBean.success(detailVo);


    }

//    /**
//     * 跳转商品详情页（优化缓存）
//     * @param model
//     * @param user
//     * @param goodsId
//     * @param request
//     * @param response
//     * @return
//     */
//    @ApiOperation("商品详情")
//    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
//    @ResponseBody
//    public String toDetail(Model model, User user, @PathVariable Long goodsId,
//                           HttpServletRequest request, HttpServletResponse response) {
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//        //Redis中获取页面，如果不为空，直接返回页面
//        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
//        if (!StringUtils.isEmpty(html)) {
//            return html;
//        }
//
//        model.addAttribute("user", user);
//        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//        Date startDate = goodsVo.getStartDate();
//        Date endDate = goodsVo.getEndDate();
//        Date nowDate = new Date();
//        //秒杀状态
//        int seckillStatus = 0;
//        //秒杀倒计时
//        int remainSeconds = 0;
//
//        if (nowDate.before(startDate)) {
//            //秒杀还未开始0
//            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
//        } else if (nowDate.after(endDate)) {
//            //秒杀已经结束
//            seckillStatus = 2;
//            remainSeconds = -1;
//        } else {
//            //秒杀进行中
//            seckillStatus = 1;
//            remainSeconds = 0;
//        }
//        model.addAttribute("remainSeconds", remainSeconds);
//        model.addAttribute("goods", goodsVo);
//        model.addAttribute("seckillStatus", seckillStatus);
//
//        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
//        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
//        if (!StringUtils.isEmpty(html)) {
//            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
//        }
//
//        return html;
//    }




    /**
     * 跳转登录页 (未缓存）
     * @param
     * @param model
     * @param
     * @return
     */
//    @RequestMapping("/toList")
//    public String toList(Model model,User user){
////        if(StringUtils.isEmpty(ticket) ){
////            return "login";
////        }
////        //方法一：通过session获取user
//////        User user = (User) session.getAttribute(ticket);
////        //方法二：通过将用户存入redis，通过redis获取用户信息
////        User user = userService.getByUserTicket(ticket,request,response);
////        log.info(user.toString());
////        if(user == null){
////            return "login";
////        }
//        model.addAttribute("user",user);
//        model.addAttribute("goodsList",goodsService.findGoodsVo());
//        return "goodsList";
//    }

//    /**
//     * 跳转商品详情页（未缓存）
//     * @param model
//     * @param user
//     * @param goodsId
//     * @return
//     */
//    @RequestMapping("/toDetail/{goodsId}")
//    public String toDetail(Model model, User user, @PathVariable Long goodsId){
//        model.addAttribute("user",user);
//        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//        model.addAttribute("goods",goodsVo);
//        Date startDate = goodsVo.getStartDate();
//        Date endDate = goodsVo.getEndDate();
//        Date nowDate = new Date();
//        //秒杀状态
//        int seckillStatus = 0;
//        //秒杀倒计时
//        int remainSeconds = 0;
//
//        if (nowDate.before(startDate)) {
//            //秒杀还未开始0
//            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
//        } else if (nowDate.after(endDate)) {
//            //秒杀已经结束
//            seckillStatus = 2;
//            remainSeconds = -1;
//        } else {
//            //秒杀进行中
//            seckillStatus = 1;
//            remainSeconds = 0;
//        }
//        model.addAttribute("seckillStatus",seckillStatus);
//        model.addAttribute("remainSeconds",remainSeconds);
//        return "goodsDetail";
//
//    }



}
